package com.chilli.cosima.action.customermanager;

import java.io.File;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.chilli.cosima.action.BaseSupport;
import com.chilli.cosima.common.BussinessException;
import com.chilli.cosima.data.bean.Customer;
import com.chilli.cosima.service.CustomerService;

public class CustomerEditAction extends BaseSupport
{

	private static final long serialVersionUID = -6350718456744857997L;
	
	private Long id;
	private Customer customer;
	private File myFile;
	private CustomerService customerService;
	private String myFileFileName;
	
	public String jumpPage()
	{

		Customer customer = customerService.findCustomerById(id);

		if (null != customer)
		{
			this.customer = customer;
			return JUMP_PAGE;
		} else
		{
			logger.error("error");
			return ERROR;
		}

	}
	
	public String execute()
	{
		Customer customerF = customerService.findCustomerById(id);
		try
		{
			if (null != myFile)
			{
				if(null != customer.getPicture())
				{
					File image = new File(ServletActionContext
							.getServletContext().getRealPath(
							"/upload/images/customer")
					+ "/" + customer.getPicture());
					if(image.exists())
					{
						image.delete();
					}
				}
				
				String imageFileName = new Date().getTime()
						+ getExtention(myFileFileName);

				File imageFile = new File(ServletActionContext
						.getServletContext().getRealPath(
								"/upload/images/customer")
						+ "/" + imageFileName);

				copy(myFile, imageFile);

				customer.setPicture(imageFileName);
			}
			else
			{
				if(null != customerF.getPicture() && !"".equals(customerF.getPicture()))
				{
					customer.setPicture(customerF.getPicture());
				}
			}
			customerService.updateCustomer(customer);
		} catch (BussinessException e)
		{
			logger.error("error", e);
			return ERROR;
		}
		return SUCCESS;
	}
	
	public Long getId()
	{
		return id;
	}
	public void setId(Long id)
	{
		this.id = id;
	}
	public Customer getCustomer()
	{
		return customer;
	}
	public void setCustomer(Customer customer)
	{
		this.customer = customer;
	}
	public File getMyFile()
	{
		return myFile;
	}
	public void setMyFile(File myFile)
	{
		this.myFile = myFile;
	}
	public CustomerService getCustomerService()
	{
		return customerService;
	}
	public void setCustomerService(CustomerService customerService)
	{
		this.customerService = customerService;
	}
	public String getMyFileFileName()
	{
		return myFileFileName;
	}
	public void setMyFileFileName(String myFileFileName)
	{
		this.myFileFileName = myFileFileName;
	}

}
